package tyw.com.userms.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import tyw.com.userms.R;
import tyw.com.userms.model.User;

public class UserAdapter extends RecyclerView.Adapter {

    public List<User> user;

    Context context;

    public UserAdapter(Context context, List<User> user) {
        this.user = user;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new UserViewHolder(LayoutInflater.from(context).inflate(R.layout.item_user, null));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

        UserViewHolder userViewHolder = (UserViewHolder) holder;
        userViewHolder.txtUser.setText(user.get(position).name);
        userViewHolder.txtPhone.setText(user.get(position).phone);
        userViewHolder.rlCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user.get(position).isSelect = !user.get(position).isSelect;
                notifyDataSetChanged();
            }
        });
        userViewHolder.ivCheck.setVisibility(user.get(position).isSelect ? View.VISIBLE : View.GONE);
    }

    @Override
    public int getItemCount() {
        return user != null ? user.size() : 0;
    }

    public class UserViewHolder extends RecyclerView.ViewHolder {

        TextView txtUser, txtPhone;

        RelativeLayout rlCheckBox;

        ImageView ivCheck;

        public UserViewHolder(View itemView) {
            super(itemView);

            txtUser = itemView.findViewById(R.id.txt_name);
            txtPhone = itemView.findViewById(R.id.txt_phone);
            rlCheckBox = itemView.findViewById(R.id.rl_check);
            ivCheck = itemView.findViewById(R.id.iv_check);
        }
    }


    public void initUser(){

        if (user == null) return;

        for (int i = 0; i < user.size(); i++) {

            if (user.get(i).isSelect) {

               user.get(i).isSelect = false;
            }
        }

        notifyDataSetChanged();
    }

    public List<User> getSelectUser() {

        List<User> users = new ArrayList<>();
        if (user == null) return users;

        for (int i = 0; i < user.size(); i++) {

            if (user.get(i).isSelect) {

                users.add(user.get(i));
            }
        }
        return users;
    }
}
